<template>
  <div>
    <div class="video-container">
      <video ref="video1" autoplay muted playsinline></video>
      <video ref="video2" autoplay muted playsinline></video>
    </div>
    <canvas ref="canvas" class="canvas" width="640" height="480"></canvas>
    <button @click="startRecording" :disabled="recording">开始录制</button>
    <button @click="stopRecording" :disabled="!recording">停止录制</button>
    <video v-if="videoUrl" :src="videoUrl" controls></video>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const recording = ref(false);
const videoChunks = ref([]);
const videoUrl = ref(null);
const mediaRecorder = ref(null);
const deviceIds = ref({
  video1: null,
  video2: null,
});
const audioDeviceId = '149290bcb469dba094e7f8194303ba29913cc942e11d34a3d73945e40763b893'; // 替换为您的音频设备 ID

const video1 = ref(null);
const video2 = ref(null);
const canvas = ref(null);

async function getVideoDevices() {
  const devices = await navigator.mediaDevices.enumerateDevices();
  const videoDevices = devices.filter((device) => device.kind === 'videoinput');
  console.log('devices', devices);
  // 选择前两个摄像头的 deviceId
  // if (videoDevices.length >= 2) {
  //   deviceIds.value.video1 = videoDevices[0].deviceId;
  //   deviceIds.value.video2 = videoDevices[1].deviceId;
  // } else {
  //   console.error('未找到足够的视频设备');
  // }
  deviceIds.value.video1 = '53ab809d9fe73083dc2ee3950b12fc9d1d7ae72d0dcdb59e77cd4b0012c55735';
  deviceIds.value.video2 = '53ab809d9fe73083dc2ee3950b12fc9d1d7ae72d0dcdb59e77cd4b0012c55735';
}

async function getStream(deviceId) {
  try {
    const status = await navigator.permissions.query({ name: 'camera' });
    console.log('status',status);
    if (status.state === 'denied') {
      throw new Error('摄像头权限检查失败1Camera permission denied');
    }
  } catch (error) {
    console.error(`摄像头权限检查失败2: ${error.message}`);
    alert('摄像头权限被拒绝');
  }

  try {
    const constraints = {
      video: { deviceId: deviceId },
      audio: false,
    };
    return await navigator.mediaDevices.getUserMedia(constraints);
  } catch (error) {
    console.error(`获取媒体流失败: ${error.message}`);
    return null;
  }
}
async function setupStreams() {
  debugger;
  if (deviceIds.value.video1 && deviceIds.value.video2) {
    // const stream1 = await navigator.mediaDevices.getUserMedia({
    //   video: { deviceId: deviceIds.value.video1 },
    //   audio: true, // 请求音频
    // });
    // console.log('stream1',stream1);
    // const stream2 = await navigator.mediaDevices.getUserMedia({
    //   video: { deviceId: deviceIds.value.video2 },
    //   audio: true, // 请求音频
    // });
    const stream1 = await getStream(deviceIds.value.video1);
    const stream2 = await getStream(deviceIds.value.video2);
    console.log('stream1', stream1);

    video1.value.srcObject = stream1;
    video2.value.srcObject = stream2;

    if (stream1 && stream2) {
      // 每 200 毫秒更新 canvas
      setInterval(() => {
        drawOnCanvas();
      }, 500);
    }
  }
}

function drawOnCanvas() {
  if(!canvas.value) return
  const ctx = canvas.value.getContext('2d');
  // 清空画布
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);

  // 绘制第一个视频流
  ctx.drawImage(video1.value, 0, 0, canvas.value.width / 2, canvas.value.height);

  // 绘制第二个视频流
  ctx.drawImage(video2.value, canvas.value.width / 2, 0, canvas.value.width / 2, canvas.value.height / 2);
}

async function startRecording() {
  videoChunks.value = [];
  recording.value = true;

  const stream = canvas.value.captureStream(30); // 30 FPS

  // 获取音频流
  const audioStream = await getCombinedAudioStream();

  // 检查 audioStream 是否有效
  if (!audioStream || !(audioStream instanceof MediaStream)) {
    console.error('获取音频流失败，返回了无效的对象。');
    return;
  }

  // 合并视频和音频流
  const combinedStream = new MediaStream([...stream.getTracks(), ...audioStream.getTracks()]);

  mediaRecorder.value = new MediaRecorder(combinedStream);

  mediaRecorder.value.ondataavailable = (event) => {
    if (event.data.size > 0) {
      videoChunks.value.push(event.data);
    }
  };

  mediaRecorder.value.onstop = handleStop;
  mediaRecorder.value.start();
}

function stopRecording() {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
    recording.value = false;
  } else {
    console.error('MediaRecorder is not initialized.');
  }
}

function handleStop() {
  const blob = new Blob(videoChunks.value, { type: 'video/webm' });
  videoUrl.value = URL.createObjectURL(blob);
}

async function getCombinedAudioStream() {
  try {
    // 使用硬编码的音频设备 ID
    const audioStream = await navigator.mediaDevices.getUserMedia({
      audio: { deviceId: audioDeviceId },
    });
    return audioStream; // 返回有效的 MediaStream
  } catch (error) {
    console.error('获取音频流失败:', error);
    return null; // 返回 null 以表示失败
  }
}

onMounted(() => {
  getVideoDevices().then(() => {
    setupStreams();
  });
});
</script>

<style>
.video-container {
  display: flex;
}
.canvas {
  display: none; /* 隐藏 canvas 元素 */
}
video {
  width: 320px;
  height: 240px;
  margin: 10px;
}
</style>
